export const isObject = obj => {
  return {}.toString.call(obj) === '[object Object]'
}

export const isEmptyObject = obj => {
  return Object.keys(obj).length === 0 ? true : false
}

export const jsonToQuery = obj => {
  // 必须为对象
  if (!isObject(obj)) throw new Error('必须为对象')
  let str = ''
  // id=1&name=abc
  for (let key in obj) {
    str += `${key}=${obj[key]}&`
  }
  return str.length === 0 ? str : str.slice(0, -1)
}


// 指定导出excel标题名称
// cnField  {id:'序号',name:'姓名'}  ==> 配置文件
// type 0 给定的对象和key进行反转
export const setJsonFieldToExcelField = (cnField, data, type = 1) => {
  if (type == 0) {
    let fieldKeys = Object.keys(cnField)
    cnField = Object.values(cnField).reduce((prev, curr, index) => {
      prev[curr] = fieldKeys[index]
      return prev
    }, {})
  }
  // item {id,name}  => {序号:1,姓名:'张三'}
  return data.map(item => {
    let keys = Object.keys(item)
    let obj = {}
    keys.forEach(key => {
      cnField[key] ? obj[cnField[key]] = item[key] : null
    })
    return obj
  })
}

// File对象转为 binary 字符串
export const fileToBinary = (fileObj, type = 'binary') => {
  return new Promise((resolve, reject) => {
    let read = new FileReader()
    if (type === 'binary') {
      // 读取的过程是一个异步的
      read.readAsBinaryString(fileObj)
    } else {
      read.readAsArrayBuffer(fileObj)
    }
    read.onload = evt => {
      // 把文件对象读成binary
      resolve(evt.target.result)
    }
  })
}